import { ref } from 'vue';
export default function useWebSocket({ onMessage, onOpen, onClose, onError }) {
  let socket = null;
  const isConnected = ref(false);
  
  // 连接到WebSocket服务器
  function connect() {
    // 关闭已存在的连接
    if (socket) {
      socket.close();
    }
    
    // 连接WebSocket服务器
    // 注意：生产环境中应使用wss://
    socket = new WebSocket('ws://10.2.221.82:3000/ws');
    
    // 监听连接打开事件
    socket.onopen = (event) => {
      console.log('WebSocket连接已打开');
      isConnected.value = true;
      if (onOpen) onOpen(event);
    };
    
    // 监听消息事件
    socket.onmessage = (event) => {
      console.log('收到WebSocket消息-----:', JSON.parse(event.data));
      if (onMessage) onMessage(event);
    };
    
    // 监听连接关闭事件
    socket.onclose = (event) => {
      console.log('WebSocket连接已关闭');
      isConnected.value = false;
      if (onClose) onClose(event);
      
      // 尝试重连
      setTimeout(() => {
        console.log('尝试重新连接...');
        connect();
      }, 3000);
    };
    
    // 监听错误事件
    socket.onerror = (error) => {
      console.error('WebSocket错误:', error);
      if (onError) onError(error);
    };
  }
  
  // 断开连接
  function disconnect() {
    if (socket) {
      socket.close();
      socket = null;
      isConnected.value = false;
    }
  }
  
  // 发送消息
  function sendMessage(data) {
    if (socket && isConnected.value) {
      try {
        socket.send(JSON.stringify({
          ...data,
          timestamp: new Date().toISOString()
        }));
        return true;
      } catch (error) {
        console.error('发送消息失败:', error);
        return false;
      }
    }
    return false;
  }
  
  return {
    connect,
    disconnect,
    sendMessage,
    isConnected
  };
}
